<?php

namespace app\api\model;

use app\admin\model\Cate;
use app\admin\model\vip\Card;
use app\exceptions\ApiException;
use ba\ScenicApi;
use think\Db;
use think\Model;

/**
 * Scenic
 */
class Scenic extends Model
{
    // 表名
    protected $name = 'scenic';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;
    protected $updateTime = false;


    public function getBannerAttr($value): array
    {
        if ($value === '' || $value === null) {
            return [];
        }
        $res = explode(',', $value);
        foreach ($res as &$val){
            $val = full_url($val);
        }
        return  $res;
    }



    public function getTrafficBusAttr($value): string
    {
        return !$value ? '' : htmlspecialchars_decode($value);
    }

    public function getScenicDesAttr($value): string
    {
        return !$value ? '' : htmlspecialchars_decode($value);
    }

    public function getBookNoticeAttr($value): string
    {
        return !$value ? '' : htmlspecialchars_decode($value);
    }


    // 追加属性
    protected $append = [
        'VipCardName',
    ];


    public function getVipCardNameAttr($value, $row): array
    {
        return Card::whereIn('id', $row['vip_card_ids'])->column('name');
    }


    public function getRdScenic($params)
    {
        $lat = $params['lat'] ?? '';
        $lng = $params['lng'] ?? '';
        $member_id = $params['member_id'] ?? '';
        $map[] = ['s.status', '=', 1];
        $search = $params['search'] ?? '';

        if(!$lat || !$lng) throw new ApiException('缺少参数');

        $haversine = "(6371 * ACOS(COS(RADIANS($lat)) * COS(RADIANS(s.latitude)) * COS(RADIANS(s.longitude) - RADIANS($lng)) + SIN(RADIANS($lat)) * SIN(RADIANS(s.latitude))))";

        $user_vip = 0;
        // 查询用户VIP卡信息（如果存在）
        if ($member_id) {
            $user_vip = (new MemberVipCard())->getMemberVipCardId($member_id,1);
        }

        if($search){
            $map[] = ['s.name','like',"%".$search."%"];
        }


        // 按距离排序
        $list = self::alias('s')
            ->where($map)
            ->join('cate c', 'c.id = s.cate_id')
            ->field(
                "s.id as scenic_id, s.name, s.cover, s.scenic_des, s.address, 
            s.vip_card_ids, s.normal_price, s.vip_price, s.city_name, c.name as cate_name,
            $haversine as distance"
            )
            ->where("$haversine <= 100")
            ->orderRaw("$haversine ASC")
            ->paginate(10)->toArray();


        if ($list['total'] == 0) {
            return api_message();
        }

        // 处理每个景区的数据
        foreach ($list['data'] as &$val) {
            $val['cover'] = full_url($val['cover']);
            $vip_card_ids = explode(',', $val['vip_card_ids']);
            $val['price'] = in_array($user_vip, $vip_card_ids) ? $val['vip_price'] : '';
            $val['price'] = $val['price'] > 0 ? $val['price'] : '';
            $val['distance'] = number_format($val['distance'], 2);
            unset($val['vip_price'], $val['normal_price'], $val['vip_card_ids']);
        }

        return api_message($list);
    }


    public function scenicDetail($params)
    {
        $scenic_id = $params['scenic_id'] ?? '';
        $lat = $params['lat'] ?? '';
        $lng = $params['lng'] ?? '';

        $member_id = $params['member_id'] ?? '';
        $user_vip = 0;
        // 查询用户VIP卡信息（如果存在）
        if ($member_id) {
            $user_vip = (new MemberVipCard())->getMemberVipCardId($member_id,1);
        }


        $detail = self::alias('s')
            ->where(['s.id' => $scenic_id, 's.status' => 1])
            ->join('cate c', 'c.id = s.cate_id')
            ->field(
                's.id as scenic_id,s.name,cate_id,banner,normal_price,vip_price,c.name as cate_name,
            vip_card_ids,address,openTime,city_name,traffic_bus,scenic_des,book_notice,latitude,longitude'
            )
            ->find()->toArray();
        if (!$detail) {
            throw new ApiException('数据不存在，请刷新后重试');
        }
//        $vip_card_ids = explode(',', $detail['vip_card_ids']);

//        $detail['price'] = in_array($user_vip, $vip_card_ids) ? $detail['vip_price'] : $detail['normal_price'];
        $detail['distance'] = $this->calculateDistance($lat, $lng, $detail['latitude'], $detail['longitude']);

//        unset($detail['cate_ids'], $detail['vip_card_ids'], $detail['normal_price'], $detail['vip_price']);

        return api_message($detail);
    }

    public function getAllScenic($params)
    {
        $member_id = $params['member_id'] ?? 0;
        $province_name = $params['province_name'] ?? '';
        $city = $params['city'] ?? '';
        $vip_card_id = $params['vip_card_id'] ?? '';
        $search = $params['search'] ?? '';
        $cate_id = $params['cate_id'] ?? '';
        $min_price = $params['min_price'] ?? '';
        $max_price = $params['max_price'] ?? '';


        $map = [['s.status', '=', 1]];
        if ($province_name) $map[] = ['s.province_name', '=', $province_name];
        if ($city){
            $other_city = ['北京市','上海市','重庆市','天津市'];
            if(in_array($province_name,$other_city)){
                $map[] = ['s.city_name', '=', $province_name];
            }else{
                $map[] = ['s.city_name','=',$city];
            }
        }
        if($max_price || $min_price){
            $map[] = ['s.normal_price','between',[$min_price,$max_price]];
        }
        if ($vip_card_id)  $map[] = ['s.vip_card_ids', 'like', "%".$vip_card_id."%"];
        if ($cate_id) $map[] = ['s.cate_id', '=', $cate_id];
        if ($search) $map[] = ['s.name', 'like', "%" . $search . "%"];
        $user_vip = 0;
        // 查询用户VIP卡信息（如果存在）
        if ($member_id) {
            $user_vip = (new MemberVipCard())->getMemberVipCardId($member_id,1);
        }

        $list = self::alias('s')
            ->where($map)
            ->join('cate c', 'c.id = s.cate_id')
            ->field(
                's.id as scenic_id, s.name, s.cover, s.scenic_des, s.address,
            s.vip_card_ids, s.normal_price, s.vip_price,s.city_name,c.name as cate_name'
            )
            ->paginate(10)
            ->toArray();

        if ($list['total'] == 0) return api_message($list);

        // 处理每个景区的数据
        foreach ($list['data'] as &$val) {
            $val['cover'] = full_url($val['cover']);
//            $vip_card_ids = explode(',', $val['vip_card_ids']);
//            $val['price'] = in_array($user_vip, $vip_card_ids) ? $val['vip_price'] : $val['normal_price'];
//            $val['price'] = $val['price'] > 0 ? $val['price'] : '';
//            unset($val['vip_price'], $val['normal_price'], $val['vip_card_ids']);
        }

        return api_message($list);


    }


    public function calculateDistance($lat1, $lon1, $lat2, $lon2)
    {
        // 地球半径，单位千米
        $earthRadius = 6371.0;

        // 转换为弧度
        $lat1 = deg2rad($lat1);
        $lon1 = deg2rad($lon1);
        $lat2 = deg2rad($lat2);
        $lon2 = deg2rad($lon2);

        // 计算经纬度差值
        $deltaLat = $lat2 - $lat1;
        $deltaLon = $lon2 - $lon1;

        // 哈弗辛公式
        $a = sin($deltaLat / 2) * sin($deltaLat / 2) +
            cos($lat1) * cos($lat2) * sin($deltaLon / 2) * sin($deltaLon / 2);
        $c = 2 * atan2(sqrt($a), sqrt(1 - $a));

        // 计算距离
        $distanceKm = $earthRadius * $c;

        // 如果距离小于1000米，返回米，否则返回公里
        if ($distanceKm * 1000 < 1000) {
            return round($distanceKm * 1000) . ' 米';
        } else {
            return round($distanceKm, 2) . ' km';
        }
    }

}
